import java.util.Vector;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

import javax.microedition.lcdui.Image;

public class SplashConnectionThread implements Runnable
{
	private StringBuffer sbout = new StringBuffer();
	private StringBuffer sbin = new StringBuffer();
	private InputStream is;
	private OutputStream os;
	private SocketConnection sc;
	private SplashConnection splashc;
	private String url;
	private boolean error;
	private Vector responseH;
	private boolean imDone;
	
	public SplashConnectionThread(String url, SplashConnection sc)
	{
		this.url = url;
		this.splashc = sc;
		this.error = false;
		this.imDone = false;
	}
	
	public void run()
	{
		try
		{
			this.sc = (SocketConnection) Connector.open(url);
			this.is = sc.openInputStream();
			this.os = sc.openOutputStream();
			
			InputStreamReader isr = new InputStreamReader(this.is);
			
			/* Send */
			sbout.append("END\r\n");
			os.write(sbout.toString().getBytes());
			os.flush();
			
			/* Receive */
			splashc.setIcon(Image.createImage("/receive.png"));
			splashc.setTitle("prejemam");
			
			responseH = new Vector(4, 2);
			
			int bajt;
			StringBuffer response = new StringBuffer();
			int end = 0;
			long timeout = System.currentTimeMillis() + (10 * 1000);
			
			while(System.currentTimeMillis() < timeout)
			{
				if(!isr.ready())
					continue;
					
				bajt = isr.read();
				
				if(bajt == ' ' || bajt == '\r' || bajt == '\n')
				{
					if(response.length() == 0)
						continue;
					responseH.addElement(response);
					response = new StringBuffer();
					continue;
				}
				
				if(bajt == 'E' && end == 0)
					end++;
				else if(end == 1 && bajt == 'N')
					end++;
				else if(end == 2 && bajt == 'D')
					break;
				
				if((bajt >= 'A' && bajt <= 'Z') || (bajt >= 'a' && bajt <= 'z') ||
					(bajt >= '0' && bajt <= '9' ) || bajt == '.' || bajt == '%' ||
					bajt == '*' || bajt == '-' || bajt == '+' || bajt == '&' ||
					bajt == ':' || bajt == '?')
				{
					response.append((char)bajt);
				}
				else
				{
					this.error = true;
					System.out.println("En cuden ton.");
					break;
				}
			}
			
			this.splashc.setTitle("Prenos koncan.");
			
			if((responseH.size() & 1) != 0 || responseH.size() == 0)
			{
				this.error = true;
				System.out.println("Ni deljivo z dva. " + responseH.size());
			}
			/* -.- */
			is.close();
			os.close();
			sc.close();
			
			this.imDone = true;
		}
		catch(ConnectionNotFoundException cnfe)
		{
			this.error = true;
			this.splashc.setTitle("Ne morem vzpostaviti povezave.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			/* Connection interrupted */
			this.error = true;
		}
		
		if(error)
		{
			this.splashc.setTitle("Napaka.");
		}
		
		/* Call transaction end */
		splashc.callTransactionEnd();
	}
	
	public boolean error()
	{
		return this.error;
	}
	
	public boolean isDone()
	{
		return this.imDone;
	}
	
	public Vector getResponseHeaders()
	{
		return this.responseH;
	}
	
	public void connect()
	{
		new Thread(this).start();
	}

	public void addHeader(String name, String value)
	{
		this.sbout.append(name);
		this.sbout.append(" ");
		this.sbout.append(value);
		this.sbout.append("\r\n");
	}
	
	public void urlDecode(StringBuffer plain)
	{
		int len = plain.length();
		for(int i = 0; i < len; i++)
		{
			char ch = plain.charAt(i);
			if(ch == '+')
			{
				plain.setCharAt(i, ' ');
			}
			else if(ch == '%')
			{
				char fr = plain.charAt(i++);
				char sc = plain.charAt(i++);
				
				plain.deleteCharAt(i + 1);
				plain.deleteCharAt(i + 2);
				
				char sum = 0;
				if(fr >= '0' )
					fr -= '0';
				else if(fr >= 'A')
					fr -= 'A';
				else
					fr -= 'a';
				sum += fr * 16;
				
				if(sc >= '0' )
					sc -= '0';
				else if(sc >= 'A')
					sc -= 'A';
				else
					sc -= 'a';
				sum += sc * 256;
				
				plain.setCharAt(i, sum);
			}
		}
	}
}
